package javatest;

public class FindAd {

    public static void main(String[] args) {
        int[] nums = {0, 9, 10, 13, 17};
        // 1: 找不到的case, target大于所有的值 -》 18 -1
        // 2: target小于所有的值       -> arr[0]
        // 3: 一个正常的case
        // 4: 找一个相等的 13  -> 13
        FindAd object = new FindAd();
        System.out.println(object.findAdPosition(nums, 12));
    }


    public int findAdPosition(int[] adPositions, int curPosition) {
        if (adPositions == null) {
            return -1;
        }
        int start = 0;
        int end = adPositions.length - 1;
        int middle;
        while (start < end) {
            middle = start + (end - start) / 2;
            if (adPositions[middle] == curPosition) {
                return adPositions[middle];
            } else if (adPositions[middle] > curPosition) {
                end = middle;
            } else {
                start = middle + 1;
            }
        }
        // 如果没有找到
        if (adPositions[end] < curPosition) {
            return -1;
        }
        return adPositions[start] >= curPosition ? adPositions[start] : adPositions[end];
    }
}
